<!-- src/views/MyRepliesView.vue -->
<template>
  <div class="my-replies-container" v-loading="loading">
    <el-page-header @back="$router.go(-1)" content="我的回复" style="margin-bottom: 20px;" />

    <el-alert
      v-if="errorMessage"
      :title="errorMessage"
      type="error"
      show-icon
      closable
      style="margin-bottom: 20px;"
    />

    <div v-if="replies.length === 0 && !loading" class="no-replies">
      <p>您还没有发表过任何回复。</p>
    </div>

    <el-table v-else :data="replies" style="width: 100%" stripe>
      <el-table-column prop="content" label="回复内容" min-width="400">
        <template #default="scope">
          <div class="reply-preview">{{ truncateContent(scope.row.content, 100) }}</div>
          <div class="reply-post-link">
            回复于: <el-link @click="goToPost(scope.row.postId)" type="primary">{{ scope.row.postTitle }}</el-link>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="likeCount" label="点赞" width="80" />
      <el-table-column prop="createdAt" label="回复时间" width="180">
         <template #default="scope">
          {{ formatDate(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button size="small" @click="editReply(scope.row.id)">编辑</el-button>
          <el-button size="small" type="danger" @click="confirmDeleteReply(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 50]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 20px; justify-content: center;"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useAuthStore } from '@/stores/auth';
import { getMyReplies } from '@/services/userService'; // 引入用户服务
import { ElMessage, ElMessageBox } from 'element-plus';
import { deleteReply } from '@/services/replyService';
import dayjs from 'dayjs';

const router = useRouter();
const route = useRoute();
const authStore = useAuthStore();

const loading = ref(false);
const errorMessage = ref('');

const replies = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 格式化日期
const formatDate = (dateString) => {
  return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss');
};

// 截断内容
const truncateContent = (content, length) => {
  if (!content) return '';
  return content.length > length ? content.substring(0, length) + '...' : content;
};

// 跳转到帖子详情页 (定位到回复)
const goToPost = (postId) => {
  router.push(`/posts/${postId}`);
};

// 跳转到编辑回复页 (需要后端支持或前端路由)
const editReply = (replyId) => {
  // router.push(`/replies/${replyId}/edit`); // 假设有编辑回复页
  ElMessage.info('编辑回复功能待实现');
};

// 确认删除回复
const confirmDeleteReply = (replyId) => {
  ElMessageBox.confirm(
    '确定要删除这条回复吗？此操作不可撤销。',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await deleteReply(replyId); // 调用删除回复的 API
      ElMessage.success('回复删除成功');
      // 删除成功后，刷新列表
      await fetchReplies(currentPage.value, pageSize.value);
    } catch (error) {
      console.error('Reply deletion failed:', error);
      errorMessage.value = error.response?.data?.message || '删除失败';
      ElMessage.error(errorMessage.value);
    }
  }).catch(() => {
    // 用户取消删除
  });
};

// 获取我的回复列表
const fetchReplies = async (page = 1, size = 10) => {
  loading.value = true;
  errorMessage.value = '';
  try {
    const response = await getMyReplies({
      page: page - 1, // 后端通常从 0 开始
      size: size
      // 可以添加排序参数
    });
    replies.value = response.data.content || [];
    total.value = response.data.totalElements || response.data.total || 0;
    currentPage.value = page;
  } catch (error) {
    console.error('Failed to fetch my replies:', error);
    errorMessage.value = error.response?.data?.message || '获取我的回复列表失败';
    ElMessage.error(errorMessage.value);
  } finally {
    loading.value = false;
  }
};

// 分页变化处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchReplies(1, val); // 页大小改变时回到第一页
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchReplies(val, pageSize.value);
};

// 组件挂载时获取数据
onMounted(() => {
  fetchReplies(currentPage.value, pageSize.value);
});
</script>

<style scoped>
.my-replies-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.no-replies {
  text-align: center;
  color: #999;
  font-size: 1.2em;
  margin-top: 50px;
}

.reply-preview {
  text-align: left;
  margin-bottom: 5px;
  white-space: pre-wrap; /* 保留换行 */
}

.reply-post-link {
  text-align: left;
  font-size: 0.9em;
  color: #666;
}
</style>
